package com.etop.weiway.wxmanage.controller;

import com.etop.weiway.basic.controller.BaseController;
import com.etop.weiway.wxmanage.service.RequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 微信请求控制器
 * Created by Jeremie on 2014/12/17.
 */
@Controller
@RequestMapping("/wxmanager")
public class WeixinRequestController extends BaseController {

    @Autowired
    private RequestService requestService;

    /**
     * 微信验证请求
     * @param wechatId
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/request/{wechatId}",method = RequestMethod.GET,produces = "text/html; charset=utf-8")
    public String verify(@PathVariable String wechatId,String signature,String timestamp,String nonce,String echostr) throws Exception {
        String Token = requestService.loadAccountToken(wechatId);
        if(Token != null)
            return requestService.verify(signature,timestamp,nonce,echostr,Token);
        return "";
    }

    /**
     * 处理微信消息请求
     * @param wechatId
     * @param request
     * @param session
     * @param servletRequest
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/request/{wechatId}",method = RequestMethod.POST,produces = "text/html; charset=utf-8")
    public String dealer(@PathVariable String wechatId,@RequestBody String request,HttpSession session,HttpServletRequest servletRequest) throws Exception {
        String path = servletRequest.getServletContext().getRealPath("/");
        if(!path.endsWith("/"))
            path +="/";
        String url = servletRequest.getRequestURL().toString().replace("wxmanager/request/" + wechatId,"");
        return requestService.handleMsg(request,session,wechatId,path,url);
    }
}
